<script>
import { clearGrayBuilding } from '@/utils/handleLayer'
import { getBasemap } from '@/api/basemap'
export default {
  inject: ['map'],
  methods: {
    onClick(obj, index) {
      // this.$emit('select', obj)
      if (this.active.index === index) {
        // 同一底图无需重新加载
        return false
      }
      this.active.index = index
      // 切换底图
      const { url } = obj
      if (url) {
        const baseStyle = '底图'
        if (this.map.getStyle(baseStyle)) {
          this.map.removeStyle(baseStyle)
        }
        this.map.addStyle(baseStyle, url, {
          before: 'bottom',
          onload: (e) => {
            console.log('e :>> ', e)
            if (e.name === '中文地图-copy') {
              clearGrayBuilding(this.map)
            }
          },
        })
      }
    },
    renderItem(obj, index) {
      const conf = {
        on: {
          click: () => this.onClick(obj, index),
        },
        class: ['item'],
      }
      return (
        (this.active.index === index || this.expand) && (
          <div {...conf}>
            <img title={obj.name} src={obj.icon} class="wh100" />
          </div>
        )
      )
    },
  },
  render() {
    const conf = {
      on: {
        mouseenter: () => (this.expand = true),
        mouseleave: () => (this.expand = false),
      },
    }
    return (
      <div class="map-switcher row" {...conf}>
        {this.maps.map(this.renderItem)}
      </div>
    )
  },
  data() {
    return {
      maps: window.BASE_STYLE,
      active: {
        index: 0,
      },
      expand: false,
    }
  },
  beforeCreate() {
    getBasemap().then((res) => {
      if (res.success) {
        this.maps = res.data.map((i) => {
          return {
            active: i.isDefault === 1,
            url: i.serviceUrl,
            icon: i.fileUrl,
            name: i.serviceName,
          }
        })
      }
    })
  },
  // props: {
  //   maps: {
  //     default() {
  //       return [];
  //     },
  //   },
  // },
  name: 'map-switcher',
}
</script>
<style lang="scss">
.map-switcher {
  position: absolute;
  bottom: 20px;
  right: 20px;
  background: rgba(255, 255, 255, 1);
  box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.29), 0 0 6px 0 rgba(0, 0, 0, 0.22);
  opacity: 1;
  padding: 3px;
  display: flex;
  flex-direction: row-reverse;
  .item {
    &:not(:last-child) {
      margin-left: 2px;
    }
    width: 40px;
    height: 30px;
    position: relative;
    cursor: pointer;
    overflow: hidden;
    > img {
      width: 100%;
    }
    // &.active {
    //   border: 2px solid #7eb9aa;
    // }
  }
}
</style>
